import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-purchase-page',
	templateUrl: './purchase-page.component.html',
	styleUrls: ['./purchase-page.css']
})
export class PurchasePageComponent implements OnInit {
	validatorOptions = {
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			applyDate: {
				validators: {
					notEmpty: {
						message: '请选择申请日期'
					},
					date: {
						format: 'YYYY-MM-DD',
						message: '请选择正确的时间,例如2018-01-01'
					}

				}
			},
			applicant: {
				validators: {
					notEmpty: {
						message: '请输入申请人'
					}
				}
			},
			buyApplyType: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择申请类型'
					}
				}
			},
			applyDepartmet: {
				validators: {
					notEmpty: {
						message: '请输入申请部门'
					}
				}
			},
		}

	}
	page: any = {
		buyApplyType: '',
		applyDate: '',
		applicant: '',
		applyDepartmet: ''
	};
	typeList = [{
		value: 1,
		label: '例行采购(授权数额内)'
	}, {
		value: 2,
		label: '例行采购(授权数额外)'
	}, {
		value: 3,
		label: '例外采购'
	}, {
		value: 4,
		label: '损伤增补'
	}, {
		value: 5,
		label: '遗失增补'
	}, {
		value: 6,
		label: '紧急采购'
	}];
	page_title: string = '新增';
	pageType: string = 'new';
	curPage = 0;//页码缓存
	purchaseId = "";
	jumpData: any = {}


	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.purchaseId = queryParams.id;
			this.curPage = queryParams.nowPage;
			this.pageType = queryParams.type;
			if (common.getCookie("purchaseUpdata")) {
				this.jumpData = JSON.parse(common.getCookie("purchaseUpdata"));
				common.clearCookie("purchaseUpdata");
				this.page.buyApplyType = this.jumpData.buyApplyType;
				this.page.applyDate = this.jumpData.applyDate;
				this.page.applicant = this.jumpData.applicant;
				this.page.applyDepartmet = this.jumpData.applyDepartmet;
			}
		});
	}
	typeChange(e) {
		this.page.buyApplyType = +e;
		$("#purchaseForm").data('bootstrapValidator').resetForm();
	}
	//表单校验
	onSubmit() {
		$('#purchaseForm').bootstrapValidator('validate'); //开启验证
		const isValid = $('#purchaseForm').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.updata();
		}
	}
	//表单数据提交
	updata() {
		if (this.submitCheckTableData.length == 0) {
			this.jsonApiService.message('请上传采购申请明细');
			return
		}
		var url, data;
		if (this.pageType === 'new') {
			data = {
				buyApplyType: this.page.buyApplyType,
				applyDate: this.page.applyDate,
				applyDepartmet: this.page.applyDepartmet,
				applicant: this.page.applicant,
				version: this.version
			}
			url = 'dtsBuyApply/insertBuyApply.html';
		} else if (this.pageType === 'updata') {
			data = {
				buyApplyType: this.page.buyApplyType,
				applyDate: this.page.applyDate,
				applyDepartmet: this.page.applyDepartmet,
				applicant: this.page.applicant,
				id: this.purchaseId,
				buyApplyNumber: this.jumpData.buyApplyNumber,
				createTime: this.jumpData.createTime,
				createName: this.jumpData.createName
			}
			url = 'dtsBuyApply/updateBuyApply.html';
		}
		const reqdata = 'data=' + JSON.stringify(data);
		this.jsonApiService.http(url, reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.router.navigate(['/supply-chain/purchase-apply'], { queryParams: { nowPage: this.curPage } });
			}
		})
	}
	//返回资源列表页
	goBack() {
		this.router.navigate(['/supply-chain/purchase-apply'], { queryParams: { nowPage: this.curPage } });
	}
	ngOnInit() {
		var that = this;
		this.initDate().then(() => {
			if (this.pageType === 'updata') {
				this.page_title = '编辑';
				this.check_table_search()
			}
		})
	}
	// 删除输入
	delKey(type) {
		if (type) {
			this.page[type] = ""
		}
	}

	//初始化时间
	initDate() {
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
						$("#datetimepicker1").datetimepicker({
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2
						}).on("changeDate", function (e) {
							var date = e.date;
							var time = common.getTimeDay(date);
							that.page.applyDate = time;
							$("#purchaseForm").data('bootstrapValidator').resetForm();
						});
						resolve();
					});
				}
			);
		})
	}
	cancelUploadUp(modal) {
		modal.hide()
	}
	viewUpload(modal) {
		modal.show()
	}

	//删除
	delSubmitCheck(row) {
		let msg, url
		let isDeleteLast = false
		if (this.pageType == 'updata') {
			msg = '此操作将删除采购明细数据,不可回退,确认要删除？'
			url = 'dtsBuyApplyDetails/deleteById.html'
			if (this.submitCheckTableData.length == 1) {
				msg = '此操作将会把申请表和明细表同时删除，确认要删除吗？'
				isDeleteLast = true
			}
		} else {
			msg = '此操作将删除临时数据,确认要删除？'
			url = 'dtsBuyApply/deleteTempByIds.html'
		}
		this.jsonApiService.confirm_message(msg).then(() => {
			const reqdata = 'id=' + row.id;
			this.jsonApiService.http(url, reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					if (isDeleteLast) {
						this.router.navigate(['/supply-chain/purchase-apply'], { queryParams: { nowPage: this.curPage } });
					} else {
						if (this.pageType == 'new') {
							this.allSize = this.allSize - 1
							this.success = this.success - 1
						}
						this.check_table_search();
					}
				}
			})
		})
	}

	//查询
	submitCheckTableData: any = []; //核对列表
	check_table_search() {
		let url, param
		if (this.pageType == 'updata') {
			param = {
				id: this.purchaseId
			}
			url = 'dtsBuyApplyDetails/getListByApplyId.html'
		} else {
			param = {
				version: this.version
			}
			url = 'dtsBuyApply/getTempDetails.html'
		}

		this.jsonApiService.http_obj(url, param).subscribe(result => {
			if (result.success) {
				this.submitCheckTableData = result.data
			}
		});
	}



	/**
	 * 上传
	 */
	fileUp: string = '';
	fileToUpload: File = null; //上传文件回调参数
	// 显示导入弹框
	showImportModal(modal) {
		// 清空选择的文件
		modal.show();
		this.fileToUpload = null;
	}
	//下载模板
	load_module() {
		var elemIF = document.createElement("iframe");
		elemIF.src = config.BaseURL + 'resources/template/buyApplyDetails-Template.xlsx';
		elemIF.style.display = "none";
		document.body.appendChild(elemIF);
	}
	// 关闭导入弹窗
	cancelUp(modal) {
		modal.hide();
		this.fileToUpload = null;
	}
	clearFile() {
		this.fileUp = '';
	}
	//文件上传change回调
	fileChange(files: FileList) {
		this.fileToUpload = files.item(0);
		const isEXCEL = this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileToUpload.type === "application/vnd.ms-excel";
		if (!isEXCEL) {
			this.jsonApiService.message('上传文件只能是 excel格式!');
			this.fileToUpload = null;
			return;
		}
	}
	allSize: any = 0; //导入条数
	success: any = 0 // 成功条数
	errMsg: any = []; //失败信息，是一个字符串数组
	version: string = ''; // 导入版本号
	errSize: any = 0; //失败条数
	//导入submit
	submitData(modal1) {
		let postParam = new FormData();
		postParam.append('file', this.fileToUpload);
		if (!this.fileToUpload) {
			this.jsonApiService.message('请上传文件')
			return false;
		}
		this.jsonApiService.form_http("dtsBuyApply/importExcelData.html", postParam).subscribe(data => {
			if (data.success) {
				modal1.hide();
				this.fileToUpload = null;
				this.allSize = data.data.allSize; //导入条数
				this.success = data.data.success // 成功条数
				this.errMsg = data.data.errMsg; //失败信息，是一个字符串数组
				this.version = data.data.version; // 导入版本号
				this.errSize = data.data.errSize; //失败条数
				this.submitCheckTableData = []
				if (this.success != '' && this.success != 0) this.check_table_search()

				$("#purchaseForm").data('bootstrapValidator').resetForm();
			} else {
				this.fileToUpload = null;
				$("#purchaseForm").data('bootstrapValidator').resetForm();
			}
		})
	}
}